package com.neuedu.javase.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-06 8:42
 * 描述 : 服务器
 */
public class Server {

    ServerSocket serverSocket = null;

    public Server() throws IOException, InterruptedException {
        this(9999);
    }

    public Server(int port) throws IOException, InterruptedException {
        System.out.println("服务器已启动，监听在【" + port + "】端口");
        serverSocket = new ServerSocket(port);

        while(true){
            //等待请求链接
            Socket socket = serverSocket.accept();
            new ThreadSocket(socket).start();
        }



    }

    public static void main(String[] args) throws IOException, InterruptedException {
        new Server();
    }


    static class ThreadSocket extends Thread {
        Socket socket = null;

        public ThreadSocket(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            try {
                //有新链接
                System.out.println("接受请求" + socket);

                //
                InputStream is = null;

                is = socket.getInputStream();

                OutputStream os = socket.getOutputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(is));


                Scanner scn = new Scanner(System.in);

                String line = null;
                while (true) {


                    //从控制台读取字符串
                    String input = scn.nextLine();
                    //发送给客户端
                    os.write((input + "\r\n").getBytes());
                    os.flush();
                    //在段护短断开的连接
                    if ("exit".equals(input)) {
                        break;
                    }


                    while (!br.ready()) {
                        Thread.sleep(500);
                    }
                    while ((line = br.readLine()) != null) {
                        System.out.println("客户端端发过来的:" + line);
                        if ("exit".equals(line)) {
                            System.out.println("byebye");
                            os.write("say bye".getBytes());
                            is.close();
                            os.close();
                            break;
                        }
                    }
                }


                //断开客户端的连接
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


}
